<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="role_name" label="角色名称">
          <el-input
            v-model="queryParams.role_name"
            placeholder="角色名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button type="success" icon="plus" @click="handleOpenDialog()">新增</el-button>
        <el-button type="danger" :disabled="ids.length === 0" icon="delete" @click="handleDelete()">
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="typeList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="角色名称" align="center" prop="role_name" width="180" />
        <el-table-column label="角色类型" align="center" prop="role_type" width="180" />
        <el-table-column label="创建时间" align="center" prop="createTime" min-width="180">
          <template #default="scope">
            {{ formatTime(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" min-width="180">
          <template #default="scope">
            {{ formatTime(scope.row.update_time) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="180">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleOpenDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 类型表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="typeFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="role_name">
          <el-input v-model="formData.role_name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色类型" prop="role_type">
          <el-select v-model="formData.role_type" placeholder="请输入角色名称">
            <el-option
              v-for="item in roleTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "role",
  inheritAttrs: false,
});
import RolesAPI from "@/api/system/role";
import { formatTime } from "@/utils/time";
const queryFormRef = ref(ElForm);
const typeFormRef = ref(ElForm);
const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
});

const roleTypeOptions = [
  { value: "超级管理员", label: "超级管理员" },
  { value: "商家", label: "商家" },
  { value: "会员", label: "会员" },
];

// 类型表格数据
const typeList = ref<any[]>();
// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});
// 类型表单
const formData = reactive<any>({
  role_name: "",
  role_type: "超级管理员",
});

const rules = reactive({
  role_name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  role_type: [{ required: true, message: "请选择角色类型", trigger: "change" }],
});

// 查询
function handleQuery() {
  loading.value = true;
  RolesAPI.getPage(queryParams)
    .then((data) => {
      typeList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

// 行复选框选中
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 打开类型弹窗
function handleOpenDialog(Good?: any) {
  dialog.visible = true;
  if (Good) {
    dialog.title = "修改类型";
    // typeAPI.getFormData(typeId).then((data) => {
    Object.assign(formData, Good);
    // });
  } else {
    dialog.title = "新增类型";
  }
}

// 提交类型表单
function handleSubmit() {
  typeFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const typeId = formData.id;
      if (typeId) {
        RolesAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        RolesAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  typeFormRef.value.resetFields();
  typeFormRef.value.clearValidate();
  formData.id = undefined;
  formData.role_name = "";
  formData.role_type = "";
}

// 删除类型
function handleDelete(typeId?: number) {
  const typeIds = [typeId || ids.value].join(",");
  if (!typeIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      RolesAPI.deleteByIds(typeIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
